from ctypes import *
from ctypes.wintypes import *
import struct

'''
查询网络适配器IP

'''


ipdll = windll.LoadLibrary("iphlpapi.dll")

MIB_IPADDR_DYNAMIC = 0x4
MIB_IPADDR_PRIMARY = 0x1

'''
详情参见: https://docs.microsoft.com/en-us/windows/win32/api/iphlpapi/nf-iphlpapi-getipaddrtable
'''
GetIpAddrTable = ipdll.GetIpAddrTable
GetIpAddrTable.argtypes = [LPVOID, LPDWORD, c_int32]
GetIpAddrTable.restype = DWORD

MIB_IPADDRTABLE = create_string_buffer(256)
dwSize = c_ulong(0)

GetIpAddrTable(MIB_IPADDRTABLE, dwSize, c_int32(0))  # 初始化Call
MIB_IPADDRTABLE = create_string_buffer(dwSize.value)
ErrorCode = GetIpAddrTable(MIB_IPADDRTABLE, dwSize, c_int32(0))
NumEntries = struct.unpack("L", MIB_IPADDRTABLE.raw[0:4])


def get_ip_by_wtype(_wtype):
    '''
    获取网络适配器IP
    _wtype

    :param _wtype: 类型.详情见:https://docs.microsoft.com/en-us/windows/win32/api/ipmib/ns-ipmib-mib_ipaddrrow_xp
    :return: 列表
    '''

    res = list()
    for i in range(NumEntries[0]):
        base_index = 4 + i * 24
        wtype_index = base_index + 22
        ip1, ip2, ip3, ip4 = struct.unpack("BBBB", MIB_IPADDRTABLE.raw[base_index:base_index + 4])
        wtype = struct.unpack("H", MIB_IPADDRTABLE.raw[wtype_index:wtype_index + 2])
        if wtype[0] & _wtype:
            res.append("{}.{}.{}.{}".format(ip1, ip2, ip3, ip4))
    return res



if __name__ == "__main__":
    print(get_ip_by_wtype(MIB_IPADDR_PRIMARY))
